package com.aabte.lota.auth;

import com.aabte.commons.rest.api.ApiResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/4/6
 */
@RestControllerAdvice
public class ProviderHandler implements ResponseBodyAdvice<ApiResult<?>> {

  @Value("${spring.application.name}")
  private String applicationName;

  @Override
  public boolean supports(
      MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
    return returnType.getParameterType().equals(ApiResult.class);
  }

  @Override
  public ApiResult<?> beforeBodyWrite(
      ApiResult<?> body,
      MethodParameter returnType,
      MediaType selectedContentType,
      Class<? extends HttpMessageConverter<?>> selectedConverterType,
      ServerHttpRequest request,
      ServerHttpResponse response) {
    return body.setProvider(applicationName);
  }
}
